<template>
  <!--操作按钮-->
  <a @click="append()"> 添加下级 </a>
  <a style="margin-left: 8px" @click="remove()"> 删除 </a>
</template>

<script lang="ts">
  import { defineComponent } from 'vue'
  import type { PropType } from 'vue'
  import { ElTree } from 'element-plus'
  import type Node from 'element-plus/es/components/tree/src/model/node'

  import type { IOrganizationTree } from '../types/10-organization'

  import { getOrganizationState } from '../state/state-organization'

  /**
   * 部门的添加、修改、删除的按钮
   */
  export default defineComponent({
    name: 'nf-org-button',
    props: {
      node: {
        type: Object as PropType<Node>
      },
      data: {
        type: Object as PropType<IOrganizationTree>
      }
    },
    setup(props, context) {
      const state = getOrganizationState()

      // eslint-disable-next-line vue/no-setup-props-destructure
      const { node, data } = props

      // 添加部门
      const append = () => {
        if (data && node) {
          const newChildTree = {
            id: new Date().valueOf(),
            label: '新部门' + state.currentOrg.num++,
            children: [] // 子部门
          }

          const org = state.orgObject[data.id]
          const newChild = {
            id: newChildTree.id,
            deptName: newChildTree.label,
            parentId: data.id, // 上级部门ID
            level: org.level + 1, // 层级
            path: org.path + '' + data.id + ',' , // 父ID集合，“,”号分割
            sort: node.data.children.length + 1, // 同一个父级里的先后顺序
            sortAll: 1, // 部门全排列
            children: [] // 子部门
          }
          // key - value 结构
          state.orgObject[newChildTree.id] = newChild
          
          data.children.push(newChildTree)
          // dataSource.value = [...dataSource.value]
        }
      }

      // 删除部门
      const remove = () => {
        // console.log('node', node)
        // console.log('data', data)
        if (data && node) {
          const parent = node.parent

          if (typeof parent.data.children === 'undefined') {
            // 上级部门没有子节点
          }
          const children: IOrganizationTree[] = parent.data.children || parent.data
          const index = children.findIndex((d) => d.id === data.id)
          children.splice(index, 1)
          // dataSource.value = [...dataSource.value]
        }
      }

      return {
        append,
        remove
      }
    }
  })
</script>